#include "memoryTracer.h"

#include <utility>
using std::make_pair;

#include <cassert>

#include <Windows.h>

#include "Trace.h"

namespace xgu{

// ------------------- Memory Trace ------------------------

MemoryTracer MemoryTracer::instance;

MemoryTracer::~MemoryTracer()
{
	TRACEEXA("\n---------- Begin of memory leaks -----------\n");
	for (Record* iter = head.flink; iter != &head; iter = iter->flink)
	{
		TRACEEXA("%s(%d) : %08X\n", iter->file, iter->line, iter->ptr);
	}
	TRACEEXA("----------- End of memory leaks ------------\n");
}

void MemoryTracer::add(void* ptr, const char* file, int line)
{
	Record* newRec = reinterpret_cast<Record*>(malloc(sizeof(Record)));
	assert(newRec);

	newRec->ptr = ptr;
	newRec->file = file;
	newRec->line = line;

	Record* prev = head.blink;
	newRec->flink = &head;
	newRec->blink = prev;
	head.blink = newRec;
	prev->flink = newRec;

}

void MemoryTracer::erase( void* ptr )
{
	for (Record* p = head.flink; p != &head; p = p->flink)
	{
		if (p->ptr == ptr)
		{
			Record* prev = p->blink;
			Record* next = p->flink;
			prev->flink = next;
			next->blink = prev;
			p->flink = p->blink = NULL;
			free(p);
			break;
		}
	}
}

MemoryTracer::MemoryTracer()
{
	head.flink = head.blink = &head;
}

}
